import unittest
from time import strftime
from time import sleep
from datetime import datetime
import urllib

class NetworkException(Exception):
    pass

class PolycomNetworkChecker(object):
    NET_FAR_SITE_NAME = 0
    NET_FAR_SITE_NUMBER = 1
    NET_FAR_SITE_SYSTEM = 2
    NET_CALL_TYPE = 3
    NET_TX_CALL_SPEED = 4
    NET_TX_CALL_SPEED2 = 5
    NET_TX_TOTAL_PACKETS_LOST = 6
    NET_TX_PERCENT_PACKET_LOSS = 7
    NET_TX_VIDEO_PROTOCOL = 8
    NET_TX_VIDEO_ANNEX = 9
    NET_TX_VIDEO_FORMAT = 10
    NET_TX_AUDIO_PROTOCOL = 11
    NET_RX_CALL_SPEED = 12
    NET_RX_CALL_SPEED2 = 13
    NET_RX_TOTAL_PACKETS_LOST = 14
    NET_RX_PERCENT_PACKET_LOSS = 15
    NET_RX_VIDEO_PROTOCOL = 16
    NET_RX_VIDEO_ANNEX = 17
    NET_RX_VIDEO_FORMAT = 18
    NET_RX_AUDIO_PROTOCOL = 19
    NET_RX_FEC_ERRORS_B1 = 20
    NET_RX_FEC_ERRORS_B2 = 21
    NET_RX_SYNC_B1 = 22
    NET_RX_SYNC_B2 = 23
    NET_NUMBER_OF_FIELDS = 24
    VTX_ATTACHED_MSG = 25
    VTX_CALL = 26
    ## Advanced Network Stats
    ADV_FAR_SITE_NAME = 0
    ADV_FAR_SITE_NUMBER = 1
    ADV_FAR_SITE_SYSTEM = 2
    ADV_CALL_TYPE = 3
    ADV_TX_AUDIO_RATE = 4
    ADV_TX_VIDEO_RATE = 5
    ADV_TX_VIDEO_RATE_USED = 6
    ADV_TX_VIDEO_FRAME_RATE = 7
    ADV_TX_VIDEO_PACKETS_LOST = 8
    ADV_TX_VIDEO_JITTER = 9
    ADV_TX_AUDIO_PACKETS_LOST = 10
    ADV_TX_AUDIO_JITTER = 11
    ADV_TX_UNKNOWN1 = 12
    ADV_TX_UNKNOWN2 = 13
    ADV_TX_UNKNOWN3 = 14
    ADV_TX_UNKNOWN4 = 15
    ADV_RX_AUDIO_RATE = 16
    ADV_RX_VIDEO_RATE = 17
    ADV_RX_VIDEO_RATE_USED = 18
    ADV_RX_VIDEO_FRAME_RATE = 19
    ADV_RX_VIDEO_PACKETS_LOST = 20
    ADV_RX_VIDEO_JITTER = 21
    ADV_RX_AUDIO_PACKETS_LOST = 22
    ADV_RX_AUDIO_JITTER = 23
    ADV_RX_UNKNOWN1 = 24
    ADV_RX_UNKNOWN2 = 25
    ADV_RX_UNKNOWN3 = 26
    ADV_RX_UNKNOWN4 = 27
    ADV_VIDEO_FEC_ERRORS = 28
    ADV_ENCRYPTION = 29
    ADV_NUMBER_OF_FIELDS = 30 # always the last one

    def __init__(self, source_ip=''):
        self.source_ip = source_ip
        self.source_address = ''
        self.school_name = ''
        self.system = ''
        self.type = ''
        self.speed = ''

    def check_info_from(self, ip):
        addresses = ['getlastconnectionmsg.xml',
                     'a_getlastconnectionmsg.htm']
        s = 'http://' + ip + '/'
        for address in addresses :
            try:
                s = 'http://' + ip + '/' + address
                c = urllib.urlopen(s).readlines()
                if ''.join(c).find('Not Found') == -1:
                    self.source_address = s
                    self.school_name = c[2].split('=')[1].strip().split('|')[0]
                    self.system = c[2].split('=')[1].strip().split('|')[2]
                    self.type = c[2].split('=')[1].strip().split('|')[3]
                    self.speed = c[2].split('=')[1].strip().split('|')[4]
                    return c
            except:
                raise NetworkException('Cannot connect polycom')

    def check_info(self):
        self.check_info_from(self.source_ip)

    def get_status_from(self, s):
        try:
            c = urllib.urlopen(s).readlines()
            return c
        except:
            print 'Cannot connect to polycom'
            raise NetworkException('Cannot connect polycom')

    def get_item(self):
        s = self.source_address
        f = lambda n: self.get_status_from(s)[n].split('=')[1].strip().split('|')
        return f(2), f(3)

    def parse_info(self):
        source_net_status, source_net_avg = self.get_item()
        s_tpl = source_net_status[PolycomNetworkChecker.NET_TX_TOTAL_PACKETS_LOST]
        s_vpl = source_net_avg[PolycomNetworkChecker.ADV_TX_VIDEO_PACKETS_LOST]
        s_vj = source_net_avg[PolycomNetworkChecker.ADV_TX_VIDEO_JITTER]
        s_apl = source_net_avg[PolycomNetworkChecker.ADV_TX_AUDIO_PACKETS_LOST]
        s_aj = source_net_avg[PolycomNetworkChecker.ADV_TX_AUDIO_JITTER]
        s_a = source_net_avg[PolycomNetworkChecker.ADV_TX_AUDIO_RATE]
        s_v = source_net_avg[PolycomNetworkChecker.ADV_TX_VIDEO_RATE]
#        print '---------------------------------------'
#        print str(datetime.now())
#        print self.source_address
#        print self.school_name
#        print self.system
#        print self.type
#        print self.speed
#
#        print 'TPL:\t', s_tpl
#        print 'VPL:\t', s_vpl
#        print 'VJ:\t', s_vj
#        print 'APL:\t',s_apl
#        print 'AJ:\t',s_aj
        d = {
            'source':self.source_ip,
            'booth':self.school_name,
            'system':self.system,
            'type':self.type,
            'speed':self.speed,
            'tpl':s_tpl,
            'vpl':s_vpl,
            'vj':s_vj,
            'apl':s_apl,
            'aj':s_aj,
            'a':s_a,
            'v':s_v,
        }
        return d

    def check(self):
        try:
            self.check_info()
            return self.parse_info()
        except NetworkException:
            return False

class Test(unittest.TestCase):
    def test(self):
        # 32
        # 33 202.126.104.182
        # 34 202.126.104.177
        # 35 202.126.104.164
        p = PolycomNetworkChecker('125.248.145.148')
        self.assertEqual(360, p.check())

if __name__ == '__main__':
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()
